package com.soft.zzti.controller.asset;

import java.security.GeneralSecurityException;
import java.sql.Date;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.soft.zzti.entity.ApplicationAssetBean;
import com.soft.zzti.entity.TDepartManageBean;
import com.soft.zzti.entity.TStaffBean;
import com.soft.zzti.entity.UserBean;
import com.soft.zzti.service.UserService;
import com.soft.zzti.service.assetApprove.AssetApproveService;
import com.soft.zzti.util.AssetUtil;
import com.soft.zzti.util.Constant;
import com.soft.zzti.util.EmailUtil;
import com.soft.zzti.util.LoginUtil;
import com.soft.zzti.util.UserUtil;
/**
 * 设备申请的审核
 * @author hucl
 *
 */
@Controller
@RequestMapping("/assetApprove")
public class AssetApproveController {
	private static Logger log = LoggerFactory.getLogger(AssetApproveController.class);
	@Autowired
	private AssetApproveService assetApproveService;
	@Autowired
	private UserService userService;
	/**
	 * 获取超级管理员带审核的申请列表
	 * @param start
	 * @param length
	 * @param startTime
	 * @param endTime
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getSMApproveList",method= {RequestMethod.POST})
	public String getSuperManagerApproveList(Integer start,Integer length,Date startTime,Date endTime,HttpSession session) {
		//前台传递的start初始值为0，需要+1 为1
		int pageNo = start == null?1:start+1;
		int pageSize = length == null?10:length;
		JSONObject responseJson = new JSONObject();
		//获取session中保存的登录人信息
		String superManagerID = (String) LoginUtil.getUserSession(session).getString("superID");
		log.debug("超级管理员审核===分页信息："+pageNo+"----"+pageSize+"---登录工号"+superManagerID);
		
		if(StringUtils.isEmpty(superManagerID)) {
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "登录工号superID为空");
			return responseJson.toJSONString();
		}
		//分页设置
		PageInfo<ApplicationAssetBean> applicationAssets = new PageInfo<ApplicationAssetBean>();
		try {
			applicationAssets = assetApproveService.getApproveBySuperManager(superManagerID, pageNo, 
					pageSize, startTime, endTime);
			responseJson.put(Constant.MSG_FLAG, Constant.SUCCESS);
			responseJson.put("resultJson", applicationAssets.getList());
			responseJson.put("recordsTotal", applicationAssets.getTotal());
			responseJson.put("recordsFiltered", applicationAssets.getTotal());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, e.getMessage());
			e.printStackTrace();
		}
		return responseJson.toJSONString();
	}
	/**
	 * 超级管理员处理申请
	 * 审核成功或失败
	 * 审批后，给申请人发送邮件通知
	 * @param applicationInfo
	 * @return
	 */
	@RequestMapping(value="/doHandingApproveByS",method= {RequestMethod.POST})
	@ResponseBody
	public String doAssetApproveOfSM(ApplicationAssetBean applicationInfo) {
		JSONObject responseJson = new JSONObject();
		boolean boo = false;
		if(StringUtils.isEmpty(applicationInfo.getMainID()) || StringUtils.isEmpty(applicationInfo.getAssetInType())
				|| StringUtils.isEmpty(applicationInfo.getApplyState())) {
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "设备信息有误！！！");
			return responseJson.toJSONString();
		}
		try {
			//审批申请
			boo = assetApproveService.doHandingAssetApproveBySuperManager(applicationInfo, applicationInfo.getApproveState());
			System.out.println(boo);
			//审批过之后，需要向申请人发送审批结果的邮件
			if(boo) {
				String email = "";
				String subject = "审批结果邮件";
				String applyStr = AssetUtil.applyStateString(applicationInfo.getApplyState());
				String approveStr = AssetUtil.approveStateStr(applicationInfo.getApproveState());
				//拼接发送的邮件内容				
				StringBuffer message = new StringBuffer();
				message.append("您的")
						.append(applyStr+"已经")
						.append(approveStr)
						.append("，若有疑问，请询问所属部门管理员！");
				String username = applicationInfo.getApplyPerson();
				int role = UserUtil.getUserRoleId(username);
				//获取申请人的邮箱
				UserBean userBean = userService.doFindUserInfo(username, role);
				if(3 == role) {
					TStaffBean sBean = userBean.getStaff();
					email = sBean.getEmail();
				}else if(2 == role) {
					TDepartManageBean dBean = userBean.getDepartManage();
					email = dBean.getEmail();
				}
				//email 不为空发送邮件
				if(!StringUtils.isEmpty(email)) {
					//发送邮件
					EmailUtil.sendEmail(email, subject, message.toString());
				}
			}
			responseJson.put(Constant.MSG_FLAG, Constant.SUCCESS);
		} catch (MessagingException | GeneralSecurityException e) {
			// TODO: handle exception
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "审批成功，邮件发送失败"+e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			responseJson.put(Constant.MSG_FLAG, Constant.ERROR);
			responseJson.put(Constant.ERROR_MSG, "审批操作失败"+e.getMessage());
			e.printStackTrace();
		}
		return responseJson.toJSONString();
	}
}
